package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.module.common.utility.Constant;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.skill.Skill;
import com.motu.monstercity.server.game.commondata.skill.SkillConstant;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class SkillManager extends SkillBaseData {
    private static Logger logger = LoggerFactory.getLogger(SkillManager.class);

    // 获取userSkillEffect，没有则创建
    public static UserSkillEffect getUserSkillEffect(long userId, int effectType) {
        if (Tool.isInList(SkillConstant.SKILL_EFFECT_LIST, effectType)) {
            UserSkillEffect userSkillEffect = (UserSkillEffect) EntityManager.getEntity(UserSkillEffect.class, userId, effectType);
            if (userSkillEffect == null) {// 没有则创建
                userSkillEffect = new UserSkillEffect();
                userSkillEffect.putUserId(userId);
                userSkillEffect.putEffectType(effectType);
                userSkillEffect.putValue(SkillManager.createSkillEffectArray().toString());
                userSkillEffect.doCreate();
            }

            return userSkillEffect;
        } else {
            return null;
        }
    }

    /**
     * 增量更新userSkillEffect
     * @param userId
     * @param skill
     * @param curLevel 技能升级后最新等级
     */
    public static void addSkillEffect(PBUserData.Builder pbUserData, long userId, Skill skill, int curLevel) {
        if (skill == null) {
            return;
        }
        int effectType = skill.getEffectType();
        int charType = skill.getEffectParam();
        UserSkillEffect userSkillEffect = getUserSkillEffect(userId, effectType);
        if (userSkillEffect == null) {
            return;
        }
        JsonArray jsonArray = userSkillEffect.getValueArray();
        int diffValue = skill.takeLevelUpDiff(curLevel);
        if (diffValue == 0) {
            return;
        }
        int newValue = jsonArray.getInteger(charType) + diffValue;
        jsonArray.set(charType, newValue);

        userSkillEffect.putValue(jsonArray.toString());
        userSkillEffect.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userSkillEffect);
    }


    //  全量更新userSkillEffect，并下发给客户端
    public static void updateSkillEffect(PBUserData.Builder pbUserData, long userId, int effectType, JsonArray jsonArray) {
        UserSkillEffect userSkillEffect = getUserSkillEffect(userId, effectType);
        if (userSkillEffect == null) {
            return;
        }

        if (!jsonArray.toString().equals(userSkillEffect.getValue())) {
            userSkillEffect.putValue(jsonArray.toString());
            userSkillEffect.update();
        }

        ProtoDataUtils.updatePBUserData(pbUserData, userSkillEffect, true);
    }

    /**
     *  获取干员(大世界技能，专属技能)，秘书技能（基因技能）在各个模块内的总加成
     * @param userId
     * @param charType
     * @return
     */
    public static int getSkillMoudleAdd(long userId, UserSkillEffect userSkillEffect, int charType) {
        if (userSkillEffect == null) {
            return 0;
        }

        JsonArray jsonArray = userSkillEffect.getValueArray();
        int total = 0;
        try {
            if (charType == 0) {
                total = jsonArray.getInteger(0);
            } else {
                total = jsonArray.getInteger(0) + jsonArray.getInteger(charType);
            }
        } catch (Exception e) {

        }
        return total;
    }

    /**
     *  获取干员(大世界技能，专属技能)，秘书技能（基因技能）在各个模块内的总加成
     * @param userId
     * @param effectType
     * @param charType
     * @return
     */
    public static int getSkillMoudleAdd(long userId, int effectType, int charType) {
        UserSkillEffect userSkillEffect = getUserSkillEffect(userId, effectType);
        if (userSkillEffect == null) {
            return 0;
        }

        JsonArray jsonArray = userSkillEffect.getValueArray();
        int total = 0;
        try {
            if (charType == 0) {
                total = jsonArray.getInteger(0);
            } else {
                total = jsonArray.getInteger(0) + jsonArray.getInteger(charType);
            }
        } catch (Exception e) {

        }
        return total;
    }

    /**
     * 计算技能列表里，某加成类型的总值有多少 取出来计算用的
     * @param skillList  技能列表
     * @param levelList  相应的升级情况
     * @param effectTtype 加成类型
     * @param charType 性格类型 0 表示该技能不按性格区分 charType 是作用对像的性格
     * @return
     */
    public static int getSkillValueBySkillList(int[] skillList, JsonArray levelList, int effectTtype, int charType) {
        if (skillList == null || skillList.length == 0) {
            //logger.error("###countSkillAddTotalByEffectType error skillList null!!!");
            return 0;// 技能列表为空
        }
        if (levelList == null || levelList.size() == 0) {
            //logger.error("###countSkillAddTotalByEffectType error levelList null!!!");
            return 0;// 等级列表为空
        }

        int total = 0;// 总的加成
        for (int i=0; i< skillList.length; i++) {
            int skillId = skillList[i];// 技能id
            int level = levelList.getInteger(i);//等级
            total += countSkillValue(skillId, level, effectTtype, charType, true);
        }
        return total;
    }

    // 登录时重算技能加成
    public static int initCountSkillValue(int[] skillList, JsonArray levelList, int effectTtype, int charType) {
        if (skillList == null || skillList.length == 0) {
            //logger.error("###countSkillAddTotalByEffectType error skillList null!!!");
            return 0;// 技能列表为空
        }
        if (levelList == null || levelList.size() == 0) {
            //logger.error("###countSkillAddTotalByEffectType error levelList null!!!");
            return 0;// 等级列表为空
        }

        if (levelList.size() < skillList.length) {
            return 0;
        }

        int total = 0;// 总的加成
        for (int i=0; i< skillList.length; i++) {
            int skillId = skillList[i];// 技能id
            int level = levelList.getInteger(i);//
            total += countSkillValue(skillId, level, effectTtype, charType, false);
        }
        return total;
    }

    /**
     * 某个技能加成总的有多少
     * @param skillId
     * @param level
     * @param effectTtype
     * @param charType
     * @param isGet true 表示把加成取出来计算用，0-所有性格都有效
     * @return
     */
    public static int countSkillValue(int skillId, int level, int effectTtype, int charType, boolean isGet) {
        if (skillId == 0 || level == 0) {
            return 0;
        }
        Skill skill = SkillManager.getSkill(skillId);
        if (skill == null) {
            return 0;
        }
        if (skill.getEffectType() != effectTtype) {
            return 0;
        }

        if (isGet) {// 取出来计算用，0 表示作用在全部
            if (skill.getEffectParam() == 0 || charType == skill.getEffectParam()) {
                return skill.countTotalAdd(level);
            } else {
                return 0;
            }
        } else {//  登录重算时
            if (charType == skill.getEffectParam()) {
                return skill.countTotalAdd(level);
            } else {
                return 0;
            }
        }
    }

    /**
     *格式化json,长度不足时用defaultValue补足
     * @param jsonArray 原来的数据
     * @param len 新数组的长度
     * @param defaultValue 默认值
     * @return
     */
    public static JsonArray formatJsonData(JsonArray jsonArray, int len, int defaultValue) {
        if (jsonArray.size() == len) {
            return jsonArray;
        }
        JsonArray result = new JsonArray();
        for (int i=0; i<len; i++) {
            if (i < jsonArray.size()) {
                result.add(jsonArray.getInteger(i));
            } else {
                result.add(defaultValue);
            }
        }
        return result;
    }

    // 统计某个性格的加成，总值，
    public static int countAddByCharacterType(int characterType, JsonArray jsonArray) {
        if (jsonArray.size() != Constant.CHARACTER_TYPE_SIZE + 1) {//[100,200,300,400,500,600] 固定这种格式，第一个表示所有性格的都有加成
            return 0;
        }
        return jsonArray.getInteger(0) + jsonArray.getInteger(characterType);
    }

    // 生成数组[100,200,300,400,500,600] 固定这种格式，第一个表示所有性格的都有加成，第二个表示性格1
    public static JsonArray createSkillEffectArray() {
        JsonArray jsonArray = new JsonArray();
        for (int i=0; i<Constant.CHARACTER_TYPE_SIZE + 1; i++) {
            jsonArray.add(0);
        }
        return jsonArray;
    }

    // 增量更新  技能加成值数组[100,200,300,400,500,600]
    public static JsonArray addSkillEffectArray(int characterType, int addValue, JsonArray jsonArray) {
        if (jsonArray == null || jsonArray.size() != Constant.CHARACTER_TYPE_SIZE + 1) {
            jsonArray = createSkillEffectArray();
        }
        int newValue = jsonArray.getInteger(characterType) + addValue;
        jsonArray.set(characterType, newValue);
        return jsonArray;
    }


    /**
     * 从所有干员(专属技能） 秘书（基因技能）统计所有技能的总加成
     * @param partnerList
     * @param secretaryList
     * @param effectType 加成类型
     * @param effectParam 技能的effect_param
     * @return
     */
    public static int countSkillFromAll(List<UserPartner> partnerList, List<UserSecretary> secretaryList, int effectType, int effectParam) {
        int total = 0;
        for (UserPartner userPartner : partnerList) {
            total += userPartner.initCountWorldSkillAdd(effectType, effectParam);// 大世界技能
            total += userPartner.initCountExstruntkill(effectType, effectParam);// 专属技能
        }
        for (UserSecretary userSecretary : secretaryList) {
            total += userSecretary.initCountIdenSkill(effectType, effectParam);// 基因技能
        }

        return total;
    }
}
